package com.zhoux.api.io.file;

import java.io.*;

/**
 * @author taoyi
 * @version 1.0
 * @date 2021/3/17 10:52
 *
 * 本类用于模拟复制粘贴文件操作
 *
 */
public class CopyFile_Test {
    public static void main(String[] args) {
        File f = new File("E:\\SoftwareEngineering\\java\\IO\\hello.txt");
        File t = new File("E:\\SoftwareEngineering\\java\\IO\\world.txt");
//        copyFile(f,t);
        byteCopyFile(f,t);
    }


    /**
     * 字符流
     * @param form
     * @param to
     */
    public static void copyFile(File form, File to){
        Reader in = null;
        Writer out = null;
        try{
            in = new BufferedReader(new FileReader(form));
            out = new BufferedWriter(new FileWriter(to,true));
            int b;
            while ((b=in.read())!=-1){
                out.write(b);
            }
            System.out.println("文件复制完毕~");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("文件复制失败~");
        }finally {
            try{
                out.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            try{
                in.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }


    /**
     * 字节流
     * @param form
     * @param to
     */
    public static void byteCopyFile(File form, File to){
        InputStream in = null;
        OutputStream out = null;
        try{
            in = new BufferedInputStream(new FileInputStream(form));
            out = new BufferedOutputStream(new FileOutputStream(to,true));
            int b;
            byte[] bs = new byte[8*1024];
            while ((b=in.read(bs)) != -1){
                out.write(bs);
            }
            out.write('\t');
            System.out.println("复制成功~");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("复制失败~");
        }finally {
            try{
                out.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            try{
                in.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

